package org.komarichin.jdo.dao;

import org.apache.commons.collections.CollectionUtils;
import org.komarichin.beans.INews;
import org.komarichin.beans.dao.INewsDAO;
import org.komarichin.jdo.persistence.News;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.jdo.support.JdoDaoSupport;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;

/**
 * User: Michael Komarichin
 * Date: 14.10.2009
 * Time: 10:58:17
 */
@Transactional(readOnly = true)
public class NewsDAO extends JdoDaoSupport implements INewsDAO {
    private static final long serialVersionUID = 5787747298357259475L;
    private static final Logger log = LoggerFactory.getLogger(NewsDAO.class);

    @Override
    @Transactional(readOnly = false)
    public INews save(INews news) {
        log.debug("save#news: {}", news);
        return (INews) getJdoTemplate().makePersistent(news);
    }

    @Override
    @Transactional(readOnly = false)
    public void update(INews news) {
        log.debug("update#news: {}", news);
        getJdoTemplate().makePersistent(news);
    }

    @Override
    @Transactional(readOnly = false)
    public void remove(INews news) {
        log.debug("remove#news: {}", news);
        getJdoTemplate().deletePersistent(news);
    }

    @Override
    public INews findById(Long id) {
        log.debug("findById#id: {}", id);
        Collection result = getJdoTemplate().find(News.class, "id == pId", "Long pId", new Object[]{id});
        log.debug("result: {}", result);
        return result != null && result.size() > 0 ? (INews) CollectionUtils.get(result, 0) : null;
    }

    @Override
    @SuppressWarnings("unchecked")
    public Collection<INews> getAll() {
        log.debug("getAll");
        Collection<INews> result = getJdoTemplate().find(News.class);
        log.debug("result: {}", result);
        return result;
    }

    @Override
    public INews getNewInstance() {
        return new News();
    }
}
